from pyquery import PyQuery as pq
from selenium import webdriver
import time
from urllib.parse import quote
from selenium.webdriver.common.by import  By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.common.exceptions import NoSuchAttributeException
browser=webdriver.Chrome()
wait = WebDriverWait(browser,10)
KEYWORD='ipad'


def get_products():
    """提取商品数据"""
    # browser.get('https://s.taobao.com/search?q='+quote('ipad'))
    time.sleep(10)
    html=browser.page_source
    doc =pq(html)
    items=doc('#mainsrp-itemlist .items .item').items()
    for item in items:
        product={
            'image':item.find('.pic .img').attr('data-src'),
            'pice':item.find('.price').text(),
            'deal':item.find('.deal-cnt').text(),
            'title':item.find('.title').text(),
            'shop':item.find('.shop').text(),
            'location':item.find('.location').text()
        }
        print(product)

def index_page(page):
    """抓取索引页，"""
    print('正在抓取第',page,'页')
    try:
        url='https://s.taobao.com/search?q='+quote(KEYWORD)
        browser.get(url)
        time.sleep(10)
        if page >1:
            input=wait.until(
                EC.presence_of_element_located((
                    By.CSS_SELECTOR,"#mainsrp-pager div.form > input")))
            submit=wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,
                        '#mainsrp-pager div.form > span.btn.J_Submit')))
            input.clear()
            input.send_keys(page)
            submit.click()
        wait.until(
            EC.text_to_be_present_in_element((
            By.CSS_SELECTOR,'#mainsrp-pager li.item.active > span'),
            str(page))
        )
        wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR,
                                                '.m-itemlist .items .item')))
        get_products()
    except TimeoutError:
        index_page(page)

MAX_PAGE=5
def main():
    for i in range(1,MAX_PAGE+1):
        index_page(i)

main()